package com.mvp.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jakewharton.rxbinding3.view.RxView;

import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import timber.log.Timber;

/**
 * Created by zhangyuncai on 2018/9/11.
 * 这个基类封装了上拉加载/下拉刷新的回调,点击事件回调,ButterKnife注解,加载网络时弹窗
 * 继承此类所在的Activity必须继承@BaseAppCompatActivity
 */
public abstract class BaseSimpleFragment extends Fragment implements View.OnClickListener, LoadMvpView {
    protected Context mContext;
    protected View rootView;
    protected Unbinder unbinder;
    protected boolean isViewPrepared; // 标识fragment视图已经初始化完毕
    protected boolean hasFetchData; // 标识已经触发过懒加载数据
    protected CompositeDisposable composite;
    public BaseAppCompatActivity mActivity;
    protected WeakReference<Activity> activityWeakReference;

    public static Fragment sNewStance(Context context, String fragmentPathName) {
        return Fragment.instantiate(context, fragmentPathName, null);
    }

    public static Fragment sNewStance(Context context, Class<?> clazz) {
        return Fragment.instantiate(context, clazz.getName(), null);
    }

    public static Fragment sNewStance(Context context, String fragmentPathName, Bundle bundle) {
        return Fragment.instantiate(context, fragmentPathName, bundle);
    }

    public static Fragment sNewStance(Context context, Class<?> clazz, Bundle bundle) {
        return Fragment.instantiate(context, clazz.getName(), bundle);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.composite = new CompositeDisposable();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(getLayout(), container, false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    protected abstract int getLayout();

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        unbinder = ButterKnife.bind(this, view);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewPrepared = true;
        lazyFetchDataIfPrepared();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        KL.d(this.getClass(), getName() + "------>onDestroyView");
        // view被销毁后，将可以重新触发数据懒加载，因为在viewpager下，fragment不会再次新建并走onCreate的生命周期流程，将从onCreateView开始
        if (composite != null && !composite.isDisposed()) {
            composite.dispose();
        }
        hasFetchData = false;
        isViewPrepared = false;
        if (unbinder != null)
            unbinder.unbind();
    }

    public boolean isViewPrepared() {
        return isViewPrepared;
    }

    public boolean isHasFetchData() {
        return hasFetchData;
    }

    //懒加载相关*********************************************************************************************************
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Timber.d(String.format("--->>>>>>>>---%s:setUserVisibleHint,页面显示隐藏======>%s", getClass().getSimpleName(), isVisibleToUser));
//        Log.v(TAG, getClass().getName() + "------>isVisibleToUser = " + isVisibleToUser);
        if (isVisibleToUser) {
            lazyFetchDataIfPrepared();
        }
    }

    protected void lazyFetchDataIfPrepared() {
        // 用户可见fragment && 没有加载过数据 && 视图已经准备完毕
        if (getUserVisibleHint() && !hasFetchData && isViewPrepared) {
            hasFetchData = true;
            lazyFetchData();
        }

    }

    /**
     * 懒加载的方式获取数据，仅在满足fragment可见和视图已经准备好的时候调用一次
     */
    protected abstract void lazyFetchData();

    @Override
    public void onAttach(Context mContext) {
        super.onAttach(mContext);
//        KL.d(this.getClass(), getName() + "------>onAttach");
        if (mContext != null) {
            this.mContext = mContext;
        } else {
            this.mContext = getActivity();
        }
        if (this.mContext != null && this.mContext instanceof BaseAppCompatActivity) {
            mActivity = (BaseAppCompatActivity) this.mContext;
            activityWeakReference=new WeakReference<>(mActivity);
        }
    }

    protected void initView() {

    }

    protected void initData() {

    }

    protected void initEvent() {

    }

    /**
     * 如果发现没有没有走此方法,可以看看该fragment所依附的activity 是否重写了此方法导致的
     */
    @Override
    public void showLoadingBar(Object showTag) {
        if (getActivity() != null && getActivity() instanceof LoadMvpView) {
            ((LoadMvpView) getActivity()).showLoadingBar(showTag);
        }
    }

    @Override
    public void dismissLoadingBar(Object dississTag) {
        if (getActivity() != null && getActivity() instanceof LoadMvpView) {
            ((LoadMvpView) getActivity()).dismissLoadingBar(dississTag);
        }
    }

    @Override
    public void showLoadingFailureError(Throwable throwable) {
        if (getActivity() != null && getActivity() instanceof LoadMvpView) {
            ((LoadMvpView) getActivity()).showLoadingFailureError(throwable);
        }
    }

    /**
     * 防止双击
     *
     * @param v
     */
    public void onFilterDoubleClick(View v) {
        Disposable subscribe = RxView.clicks(v)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(unit -> {
                    onClick(v);
                });
        composite.add(subscribe);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Timber.d(String.format("--->>>>>>>>---%s:onHiddenChanged,页面显示隐藏======>%s", getClass().getSimpleName(), hidden));
    }
}
